
import 'dart:convert';

import 'package:valovault_reminder/common/config/val_define_const_data.dart';
import 'package:valovault_reminder/common/util/val_shared_preferences_tool.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_typedefs/rx_typedefs.dart';

import '../../http/val_dio_fetch_kit.dart';
import '../bean/val_user_base_info_model.dart';
import '../config/val_client_url_path.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';

class ValAppStateTool {

  ValAppStateTool._inner();

  static final ValAppStateTool _i = ValAppStateTool._inner();

  factory ValAppStateTool() => _i;

  bool isFirstRegister = false;

  bool isAlarmFinished = false;

  /// token
  String token = '';

  /// userId
  String userId = '';

  /// 用户信息
  ValUserBaseInfoModel? accountInfo;

  /// 用户信息
  ValUserBaseInfoModel? _user;

  /// 融云token
  String rckToken = '';

  /// 融云的Key
  String rckKey = '';

  ///客服id
  String userServiceAccountId = '';

  ///  谷歌翻译的Key
  String googleTranslationKey = '';

  String currentLocale = '';

  /// 初始化
  static Future setup() async {
    await _i._reloadCache();
    /// 获取用户信息
    getUserInfo(completion: (user) {

    });
  }

  Future _reloadCache() async {
    String token = await ValLocalStore.getValue(ValDefineConstData.valTokenKey, '');
    String userId = await ValLocalStore.getValue(ValDefineConstData.valUserId, '');
    _i.token = token;
    _i.userId = userId;
  }

  /// 保存登录信息
  static void saveLoginInfo(Map json) {
    try {
      if (json['token'] is String) {
        _i.token =  json['token'];
        ValLocalStore.saveValue(ValDefineConstData.valTokenKey, _i.token);
      }
      if (json['isFirstRegister'] is bool) {
        _i.isFirstRegister =  json['isFirstRegister'];

      }
      _i._user = ValUserBaseInfoModel.fromJson(json['userInfo']);
      ValLocalStore.saveValue(ValDefineConstData.valUserId, _i._user?.userId ?? '');
      _i._reloadCache();
    }catch (e) {

    }

  }

  /// 获取用户信息
  static Future getUserInfo({
    bool refresh = false,
    ValueChanged <ValUserBaseInfoModel?>? completion
  }) async {
    if (_i._user == null || refresh == true) {
      if (_i.userId.isEmpty) return;
      ValDioFetchKit.getInstance().getJsonWithUrl(ValClientUrlPath.userInfo,
          {'userId' : _i.userId}, (data, errorCode, message) {
            if (errorCode == 0) {
              _i._user = ValUserBaseInfoModel.fromJson(data);
              ValAppStateTool().accountInfo = _i._user;
              completion?.call(_i._user);
            }else {
              completion?.call(_i._user);
            }
          },  (err)  {
            completion?.call(_i._user);
      });
    }else {
      completion?.call(_i._user);
    }
  }

  /// 获取配置
  static void getConfigFromNet(Callback completion) {
    if (_i.rckKey.isNotEmpty &&
        _i.googleTranslationKey.isNotEmpty &&
        _i.token.isNotEmpty && _i.rckToken.isNotEmpty) {
      completion();
      return;
    }
    ValDioFetchKit.getInstance().getJsonWithUrl(ValClientUrlPath.configUrl, {'ver':'0'},
            (data, errorCode, message) {
          if (errorCode == 0) {
            if (data['items'] is List) {
              List items = data['items'];
              for (var element in items) {
                if (element['name'] is String) {
                  String  name = element['name'] ?? '';
                  if (name == 'google_translation_key') {
                    _i.googleTranslationKey = element['data'] ?? '';
                  }else if (name == 'rck') {
                    _i.rckKey = element['data'] ?? '';
                  }
                }
              }
            }
          }
          getRckTokenFromNet(() {
            completion();
          });
        }, (err) {
          completion();
    });
  }

  /// 获取客服配置
  static void getStrategyConfig(Callback completion) {
    if (_i.rckKey.isNotEmpty &&
        _i.googleTranslationKey.isNotEmpty &&
        _i.token.isNotEmpty) {
      completion();
      return;
    }
    ValDioFetchKit.getInstance().getJsonWithUrl(ValClientUrlPath.getStrategy, {},
            (data, errorCode, message) {
          if (errorCode == 0) {
            _i.userServiceAccountId = data['userServiceAccountId'];
          }
          completion();
        }, (err) {
          completion();
        });
  }

  /// 获取融云token
  /// 获取配置
  static void getRckTokenFromNet(Callback completion) {
    if (_i.token.isEmpty) return;
    ValDioFetchKit.getInstance().getJsonWithUrl(ValClientUrlPath.rckToken, {},
            (data, errorCode, message) {
          if (errorCode == 0) {
              _i.rckToken = data;
          }
          completion();
        }, (err) {
          completion();
        });
  }



  void logout() {
    token = '';
    userId = '';
    ValLocalStore.delete(ValDefineConstData.valTokenKey);
    ValLocalStore.delete(ValDefineConstData.valUserId);
  }
}

